home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / Net / Ping.pm < prev    next >
Encoding:
Perl POD Document  |  1999-12-28  |  18.1 KB  |  507 lines

  1. package Net::Ping;
  2.  
  3.  
  4. require 5.002;
  5. require Exporter;
  6.  
  7. use strict;
  8. use vars qw(@ISA @EXPORT $VERSION
  9.             $def_timeout $def_proto $max_datasize);
  10. use FileHandle;
  11. use Socket qw( SOCK_DGRAM SOCK_STREAM SOCK_RAW PF_INET
  12.                inet_aton sockaddr_in );
  13. use Carp;
  14.  
  15. @ISA = qw(Exporter);
  16. @EXPORT = qw(pingecho);
  17. $VERSION = 2.02;
  18.  
  19.  
  20. $def_timeout = 5;           # Default timeout to wait for a reply
  21. $def_proto = "udp";         # Default protocol to use for pinging
  22. $max_datasize = 1024;       # Maximum data bytes in a packet
  23.  
  24.  
  25. sub pingecho
  26. {
  27.     my ($host,              # Name or IP number of host to ping
  28.         $timeout            # Optional timeout in seconds
  29.         ) = @_;
  30.     my ($p);                # A ping object
  31.  
  32.     $p = Net::Ping->new("tcp", $timeout);
  33.     $p->ping($host);        # Going out of scope closes the connection
  34. }
  35.  
  36.  
  37. sub new
  38. {
  39.     my ($this,
  40.         $proto,             # Optional protocol to use for pinging
  41.         $timeout,           # Optional timeout in seconds
  42.         $data_size          # Optional additional bytes of data
  43.         ) = @_;
  44.     my  $class = ref($this) || $this;
  45.     my  $self = {};
  46.     my ($cnt,               # Count through data bytes
  47.         $min_datasize       # Minimum data bytes required
  48.         );
  49.  
  50.     bless($self, $class);
  51.  
  52.     $proto = $def_proto unless $proto;          # Determine the protocol
  53.     croak("Protocol for ping must be \"tcp\", \"udp\" or \"icmp\"")
  54.         unless $proto =~ m/^(tcp|udp|icmp)$/;
  55.     $self->{"proto"} = $proto;
  56.  
  57.     $timeout = $def_timeout unless $timeout;    # Determine the timeout
  58.     croak("Default timeout for ping must be greater than 0 seconds")
  59.         if $timeout <= 0;
  60.     $self->{"timeout"} = $timeout;
  61.  
  62.     $min_datasize = ($proto eq "udp") ? 1 : 0;  # Determine data size
  63.     $data_size = $min_datasize unless defined($data_size) && $proto ne "tcp";
  64.     croak("Data for ping must be from $min_datasize to $max_datasize bytes")
  65.         if ($data_size < $min_datasize) || ($data_size > $max_datasize);
  66.     $data_size-- if $self->{"proto"} eq "udp";  # We provide the first byte
  67.     $self->{"data_size"} = $data_size;
  68.  
  69.     $self->{"data"} = "";                       # Construct data bytes
  70.     for ($cnt = 0; $cnt < $self->{"data_size"}; $cnt++)
  71.     {
  72.         $self->{"data"} .= chr($cnt % 256);
  73.     }
  74.  
  75.     $self->{"seq"} = 0;                         # For counting packets
  76.     if ($self->{"proto"} eq "udp")              # Open a socket
  77.     {
  78.         $self->{"proto_num"} = (getprotobyname('udp'))[2] ||
  79.             croak("Can't udp protocol by name");
  80.         $self->{"port_num"} = (getservbyname('echo', 'udp'))[2] ||
  81.             croak("Can't get udp echo port by name");
  82.         $self->{"fh"} = FileHandle->new();
  83.         socket($self->{"fh"}, &PF_INET(), &SOCK_DGRAM(),
  84.                $self->{"proto_num"}) ||
  85.             croak("udp socket error - $!");
  86.     }
  87.     elsif ($self->{"proto"} eq "icmp")
  88.     {
  89.         croak("icmp ping requires root privilege") if $>;
  90.         $self->{"proto_num"} = (getprotobyname('icmp'))[2] ||
  91.                     croak("Can't get icmp protocol by name");
  92.         $self->{"pid"} = $$ & 0xffff;           # Save lower 16 bits of pid
  93.         $self->{"fh"} = FileHandle->new();
  94.         socket($self->{"fh"}, &PF_INET(), &SOCK_RAW(), $self->{"proto_num"}) ||
  95.             croak("icmp socket error - $!");
  96.     }
  97.     elsif ($self->{"proto"} eq "tcp")           # Just a file handle for now
  98.     {
  99.         $self->{"proto_num"} = (getprotobyname('tcp'))[2] ||
  100.             croak("Can't get tcp protocol by name");
  101.         $self->{"port_num"} = (getservbyname('echo', 'tcp'))[2] ||
  102.             croak("Can't get tcp echo port by name");
  103.         $self->{"fh"} = FileHandle->new();
  104.     }
  105.  
  106.  
  107.     return($self);
  108. }
  109.  
  110.  
  111. sub ping
  112. {
  113.     my ($self,
  114.         $host,              # Name or IP number of host to ping
  115.         $timeout            # Seconds after which ping times out
  116.         ) = @_;
  117.     my ($ip,                # Packed IP number of $host
  118.         $ret                # The return value
  119.         );
  120.  
  121.     croak("Usage: \$p->ping(\$host [, \$timeout])") unless @_ == 2 || @_ == 3;
  122.     $timeout = $self->{"timeout"} unless $timeout;
  123.     croak("Timeout must be greater than 0 seconds") if $timeout <= 0;
  124.  
  125.     $ip = inet_aton($host);
  126.     return(undef) unless defined($ip);      # Does host exist?
  127.  
  128.     if ($self->{"proto"} eq "udp")
  129.     {
  130.         $ret = $self->ping_udp($ip, $timeout);
  131.     }
  132.     elsif ($self->{"proto"} eq "icmp")
  133.     {
  134.         $ret = $self->ping_icmp($ip, $timeout);
  135.     }
  136.     elsif ($self->{"proto"} eq "tcp")
  137.     {
  138.         $ret = $self->ping_tcp($ip, $timeout);
  139.     }
  140.     else
  141.     {
  142.         croak("Unknown protocol \"$self->{proto}\" in ping()");
  143.     }
  144.     return($ret);
  145. }
  146.  
  147. sub ping_icmp
  148. {
  149.     my ($self,
  150.         $ip,                # Packed IP number of the host
  151.         $timeout            # Seconds after which ping times out
  152.         ) = @_;
  153.  
  154.     my $ICMP_ECHOREPLY = 0; # ICMP packet types
  155.     my $ICMP_ECHO = 8;
  156.     my $icmp_struct = "C2 S3 A";  # Structure of a minimal ICMP packet
  157.     my $subcode = 0;        # No ICMP subcode for ECHO and ECHOREPLY
  158.     my $flags = 0;          # No special flags when opening a socket
  159.     my $port = 0;           # No port with ICMP
  160.  
  161.     my ($saddr,             # sockaddr_in with port and ip
  162.         $checksum,          # Checksum of ICMP packet
  163.         $msg,               # ICMP packet to send
  164.         $len_msg,           # Length of $msg
  165.         $rbits,             # Read bits, filehandles for reading
  166.         $nfound,            # Number of ready filehandles found
  167.         $finish_time,       # Time ping should be finished
  168.         $done,              # set to 1 when we are done
  169.         $ret,               # Return value
  170.         $recv_msg,          # Received message including IP header
  171.         $from_saddr,        # sockaddr_in of sender
  172.         $from_port,         # Port packet was sent from
  173.         $from_ip,           # Packed IP of sender
  174.         $from_type,         # ICMP type
  175.         $from_subcode,      # ICMP subcode
  176.         $from_chk,          # ICMP packet checksum
  177.         $from_pid,          # ICMP packet id
  178.         $from_seq,          # ICMP packet sequence
  179.         $from_msg           # ICMP message
  180.         );
  181.  
  182.     $self->{"seq"} = ($self->{"seq"} + 1) % 65536; # Increment sequence
  183.     $checksum = 0;                          # No checksum for starters
  184.     $msg = pack($icmp_struct . $self->{"data_size"}, $ICMP_ECHO, $subcode,
  185.                 $checksum, $self->{"pid"}, $self->{"seq"}, $self->{"data"});
  186.     $checksum = Net::Ping->checksum($msg);
  187.     $msg = pack($icmp_struct . $self->{"data_size"}, $ICMP_ECHO, $subcode,
  188.                 $checksum, $self->{"pid"}, $self->{"seq"}, $self->{"data"});
  189.     $len_msg = length($msg);
  190.     $saddr = sockaddr_in($port, $ip);
  191.     send($self->{"fh"}, $msg, $flags, $saddr); # Send the message
  192.  
  193.     $rbits = "";
  194.     vec($rbits, $self->{"fh"}->fileno(), 1) = 1;
  195.     $ret = 0;
  196.     $done = 0;
  197.     $finish_time = time() + $timeout;       # Must be done by this time
  198.     while (!$done && $timeout > 0)          # Keep trying if we have time
  199.     {
  200.         $nfound = select($rbits, undef, undef, $timeout); # Wait for packet
  201.         $timeout = $finish_time - time();   # Get remaining time
  202.         if (!defined($nfound))              # Hmm, a strange error
  203.         {
  204.             $ret = undef;
  205.             $done = 1;
  206.         }
  207.         elsif ($nfound)                     # Got a packet from somewhere
  208.         {
  209.             $recv_msg = "";
  210.             $from_saddr = recv($self->{"fh"}, $recv_msg, 1500, $flags);
  211.             ($from_port, $from_ip) = sockaddr_in($from_saddr);
  212.             ($from_type, $from_subcode, $from_chk,
  213.              $from_pid, $from_seq, $from_msg) =
  214.                 unpack($icmp_struct . $self->{"data_size"},
  215.                        substr($recv_msg, length($recv_msg) - $len_msg,
  216.                               $len_msg));
  217.             if (($from_type == $ICMP_ECHOREPLY) &&
  218.                 ($from_ip eq $ip) &&
  219.                 ($from_pid == $self->{"pid"}) && # Does the packet check out?
  220.                 ($from_seq == $self->{"seq"}))
  221.             {
  222.                 $ret = 1;                   # It's a winner
  223.                 $done = 1;
  224.             }
  225.         }
  226.         else                                # Oops, timed out
  227.         {
  228.             $done = 1;
  229.         }
  230.     }
  231.     return($ret)
  232. }
  233.  
  234.  
  235. sub checksum
  236. {
  237.     my ($class,
  238.         $msg            # The message to checksum
  239.         ) = @_;
  240.     my ($len_msg,       # Length of the message
  241.         $num_short,     # The number of short words in the message
  242.         $short,         # One short word
  243.         $chk            # The checksum
  244.         );
  245.  
  246.     $len_msg = length($msg);
  247.     $num_short = $len_msg / 2;
  248.     $chk = 0;
  249.     foreach $short (unpack("S$num_short", $msg))
  250.     {
  251.         $chk += $short;
  252.     }                                           # Add the odd byte in
  253.     $chk += unpack("C", substr($msg, $len_msg - 1, 1)) if $len_msg % 2;
  254.     $chk = ($chk >> 16) + ($chk & 0xffff);      # Fold high into low
  255.     return(~(($chk >> 16) + $chk) & 0xffff);    # Again and complement
  256. }
  257.  
  258.  
  259. sub ping_tcp
  260. {
  261.     my ($self,
  262.         $ip,                # Packed IP number of the host
  263.         $timeout            # Seconds after which ping times out
  264.         ) = @_;
  265.     my ($saddr,             # sockaddr_in with port and ip
  266.         $ret                # The return value
  267.         );
  268.                             
  269.     socket($self->{"fh"}, &PF_INET(), &SOCK_STREAM(), $self->{"proto_num"}) ||
  270.         croak("tcp socket error - $!");
  271.     $saddr = sockaddr_in($self->{"port_num"}, $ip);
  272.  
  273.     $SIG{'ALRM'} = sub { die };
  274.     alarm($timeout);        # Interrupt connect() if we have to
  275.             
  276.     $ret = 0;               # Default to unreachable
  277.     eval <<'EOM' ;
  278.         return unless connect($self->{"fh"}, $saddr);
  279.         $ret = 1;
  280. EOM
  281.     alarm(0);
  282.     $self->{"fh"}->close();
  283.     return($ret);
  284. }
  285.  
  286.  
  287. sub ping_udp
  288. {
  289.     my ($self,
  290.         $ip,                # Packed IP number of the host
  291.         $timeout            # Seconds after which ping times out
  292.         ) = @_;
  293.  
  294.     my $flags = 0;          # Nothing special on open
  295.  
  296.     my ($saddr,             # sockaddr_in with port and ip
  297.         $ret,               # The return value
  298.         $msg,               # Message to be echoed
  299.         $finish_time,       # Time ping should be finished
  300.         $done,              # Set to 1 when we are done pinging
  301.         $rbits,             # Read bits, filehandles for reading
  302.         $nfound,            # Number of ready filehandles found
  303.         $from_saddr,        # sockaddr_in of sender
  304.         $from_msg,          # Characters echoed by $host
  305.         $from_port,         # Port message was echoed from
  306.         $from_ip            # Packed IP number of sender
  307.         );
  308.  
  309.     $saddr = sockaddr_in($self->{"port_num"}, $ip);
  310.     $self->{"seq"} = ($self->{"seq"} + 1) % 256;    # Increment sequence
  311.     $msg = chr($self->{"seq"}) . $self->{"data"};   # Add data if any
  312.     send($self->{"fh"}, $msg, $flags, $saddr);      # Send it
  313.  
  314.     $rbits = "";
  315.     vec($rbits, $self->{"fh"}->fileno(), 1) = 1;
  316.     $ret = 0;                   # Default to unreachable
  317.     $done = 0;
  318.     $finish_time = time() + $timeout;       # Ping needs to be done by then
  319.     while (!$done && $timeout > 0)
  320.     {
  321.         $nfound = select($rbits, undef, undef, $timeout); # Wait for response
  322.         $timeout = $finish_time - time();   # Get remaining time
  323.  
  324.         if (!defined($nfound))  # Hmm, a strange error
  325.         {
  326.             $ret = undef;
  327.             $done = 1;
  328.         }
  329.         elsif ($nfound)         # A packet is waiting
  330.         {
  331.             $from_msg = "";
  332.             $from_saddr = recv($self->{"fh"}, $from_msg, 1500, $flags);
  333.             ($from_port, $from_ip) = sockaddr_in($from_saddr);
  334.             if (($from_ip eq $ip) &&        # Does the packet check out?
  335.                 ($from_port == $self->{"port_num"}) &&
  336.                 ($from_msg eq $msg))
  337.             {
  338.                 $ret = 1;       # It's a winner
  339.                 $done = 1;
  340.             }
  341.         }
  342.         else                    # Oops, timed out
  343.         {
  344.             $done = 1;
  345.         }
  346.     }
  347.     return($ret);
  348. }   
  349.  
  350.  
  351. sub close
  352. {
  353.     my ($self) = @_;
  354.  
  355.     $self->{"fh"}->close() unless $self->{"proto"} eq "tcp";
  356. }
  357.  
  358.  
  359. 1;
  360. __END__
  361.  
  362. =head1 NAME
  363.  
  364. Net::Ping - check a remote host for reachability
  365.  
  366. =head1 SYNOPSIS
  367.  
  368.     use Net::Ping;
  369.  
  370.     $p = Net::Ping->new();
  371.     print "$host is alive.\n" if $p->ping($host);
  372.     $p->close();
  373.  
  374.     $p = Net::Ping->new("icmp");
  375.     foreach $host (@host_array)
  376.     {
  377.         print "$host is ";
  378.         print "NOT " unless $p->ping($host, 2);
  379.         print "reachable.\n";
  380.         sleep(1);
  381.     }
  382.     $p->close();
  383.     
  384.     $p = Net::Ping->new("tcp", 2);
  385.     while ($stop_time > time())
  386.     {
  387.         print "$host not reachable ", scalar(localtime()), "\n"
  388.             unless $p->ping($host);
  389.         sleep(300);
  390.     }
  391.     undef($p);
  392.     
  393.     print "$host is alive.\n" if pingecho($host);
  394.  
  395. =head1 DESCRIPTION
  396.  
  397. This module contains methods to test the reachability of remote
  398. hosts on a network.  A ping object is first created with optional
  399. parameters, a variable number of hosts may be pinged multiple
  400. times and then the connection is closed.
  401.  
  402. You may choose one of three different protocols to use for the ping.
  403. With the "tcp" protocol the ping() method attempts to establish a
  404. connection to the remote host's echo port.  If the connection is
  405. successfully established, the remote host is considered reachable.  No
  406. data is actually echoed.  This protocol does not require any special
  407. privileges but has higher overhead than the other two protocols.
  408.  
  409. Specifying the "udp" protocol causes the ping() method to send a udp
  410. packet to the remote host's echo port.  If the echoed packet is
  411. received from the remote host and the received packet contains the
  412. same data as the packet that was sent, the remote host is considered
  413. reachable.  This protocol does not require any special privileges.
  414.  
  415. If the "icmp" protocol is specified, the ping() method sends an icmp
  416. echo message to the remote host, which is what the UNIX ping program
  417. does.  If the echoed message is received from the remote host and
  418. the echoed information is correct, the remote host is considered
  419. reachable.  Specifying the "icmp" protocol requires that the program
  420. be run as root or that the program be setuid to root.
  421.  
  422. =head2 Functions
  423.  
  424. =over 4
  425.  
  426. =item Net::Ping->new([$proto [, $def_timeout [, $bytes]]]);
  427.  
  428. Create a new ping object.  All of the parameters are optional.  $proto
  429. specifies the protocol to use when doing a ping.  The current choices
  430. are "tcp", "udp" or "icmp".  The default is "udp".
  431.  
  432. If a default timeout ($def_timeout) in seconds is provided, it is used
  433. when a timeout is not given to the ping() method (below).  The timeout
  434. must be greater than 0 and the default, if not specified, is 5 seconds.
  435.  
  436. If the number of data bytes ($bytes) is given, that many data bytes
  437. are included in the ping packet sent to the remote host. The number of
  438. data bytes is ignored if the protocol is "tcp".  The minimum (and
  439. default) number of data bytes is 1 if the protocol is "udp" and 0
  440. otherwise.  The maximum number of data bytes that can be specified is
  441. 1024.
  442.  
  443. =item $p->ping($host [, $timeout]);
  444.  
  445. Ping the remote host and wait for a response.  $host can be either the
  446. hostname or the IP number of the remote host.  The optional timeout
  447. must be greater than 0 seconds and defaults to whatever was specified
  448. when the ping object was created.  If the hostname cannot be found or
  449. there is a problem with the IP number, undef is returned.  Otherwise,
  450. 1 is returned if the host is reachable and 0 if it is not.  For all
  451. practical purposes, undef and 0 and can be treated as the same case.
  452.  
  453. =item $p->close();
  454.  
  455. Close the network connection for this ping object.  The network
  456. connection is also closed by "undef $p".  The network connection is
  457. automatically closed if the ping object goes out of scope (e.g. $p is
  458. local to a subroutine and you leave the subroutine).
  459.  
  460. =item pingecho($host [, $timeout]);
  461.  
  462. To provide backward compatibility with the previous version of
  463. Net::Ping, a pingecho() subroutine is available with the same
  464. functionality as before.  pingecho() uses the tcp protocol.  The
  465. return values and parameters are the same as described for the ping()
  466. method.  This subroutine is obsolete and may be removed in a future
  467. version of Net::Ping.
  468.  
  469. =back
  470.  
  471. =head1 WARNING
  472.  
  473. pingecho() or a ping object with the tcp protocol use alarm() to
  474. implement the timeout.  So, don't use alarm() in your program while
  475. you are using pingecho() or a ping object with the tcp protocol.  The
  476. udp and icmp protocols do not use alarm() to implement the timeout.
  477.  
  478. =head1 NOTES
  479.  
  480. There will be less network overhead (and some efficiency in your
  481. program) if you specify either the udp or the icmp protocol.  The tcp
  482. protocol will generate 2.5 times or more traffic for each ping than
  483. either udp or icmp.  If many hosts are pinged frequently, you may wish
  484. to implement a small wait (e.g. 25ms or more) between each ping to
  485. avoid flooding your network with packets.
  486.  
  487. The icmp protocol requires that the program be run as root or that it
  488. be setuid to root.  The tcp and udp protocols do not require special
  489. privileges, but not all network devices implement the echo protocol
  490. for tcp or udp.
  491.  
  492. Local hosts should normally respond to pings within milliseconds.
  493. However, on a very congested network it may take up to 3 seconds or
  494. longer to receive an echo packet from the remote host.  If the timeout
  495. is set too low under these conditions, it will appear that the remote
  496. host is not reachable (which is almost the truth).
  497.  
  498. Reachability doesn't necessarily mean that the remote host is actually
  499. functioning beyond its ability to echo packets.
  500.  
  501. Because of a lack of anything better, this module uses its own
  502. routines to pack and unpack ICMP packets.  It would be better for a
  503. separate module to be written which understands all of the different
  504. kinds of ICMP packets.
  505.  
  506. =cut
  507.